import difflib
import os
import sys

import pdfplumber
import numpy as np
import cv2


# def lcstring(x, y):
#     m = len(x)
#     n = len(y)
#     table = np.zeros((m, n))
#     biggest = 0
#     for i in range(1, m):
#         for j in range(1, n):
#             if x[i] == y[j]:
#                 table[i][j] = table[i-1][j-1] + 1
#                 if table[i][j] > biggest:
#                     index1 = i
#                     index2 = j
#                     biggest = table[i][j]
#             else:
#                 table[i][j] = 0

#     return table, biggest, index1, index2


def lcsubsequence(x, y, m, n):
    table = np.zeros((m+1, n+1))
    comman_index = []
    for i in range(m+1):
        for j in range(n+1):
            if i == 0 or j == 0:
                table[i][j] = 0
            elif x[i-1] == y[j-1]:
                table[i][j] = table[i-1][j-1] + 1
            else:
                table[i][j] = max(table[i-1][j], table[i][j-1])
    return table, comman_index

def equal(a, b, T=10):
    if np.linalg.norm(a-b) <= T:
        return True
    else:
        return False


def find_lcseque(s1, s2): 
	# 生成字符串长度加1的0矩阵，m用来保存对应位置匹配的结果
    m = [ [ 0 for x in range(len(s2)+1) ] for y in range(len(s1)+1) ] 
    # d用来记录转移方向
    d = [ [ None for x in range(len(s2)+1) ] for y in range(len(s1)+1) ] 
 
    for p1 in range(len(s1)): 
        for p2 in range(len(s2)): 
            if s1[p1] == s2[p2]:            #字符匹配成功，则该位置的值为左上方的值加1
                m[p1+1][p2+1] = m[p1][p2]+1
                d[p1+1][p2+1] = 'ok'          
            elif m[p1+1][p2] > m[p1][p2+1]:  #左值大于上值，则该位置的值为左值，并标记回溯时的方向
                m[p1+1][p2+1] = m[p1+1][p2] 
                d[p1+1][p2+1] = 'left'          
            else:                           #上值大于左值，则该位置的值为上值，并标记方向up
                m[p1+1][p2+1] = m[p1][p2+1]   
                d[p1+1][p2+1] = 'up'         
    (p1, p2) = (len(s1), len(s2)) 

    s = []
    comman_index = []
    while m[p1][p2]: #不为None时
        c = d[p1][p2]
        if c == 'ok': #匹配成功，插入该字符，并向左上角找下一个
            s.append(s1[p1-1])
            comman_index.append(p1-1)
            p1-=1
            p2-=1 
        if c =='left':  #根据标记，向左找下一个
            p2 -= 1
        if c == 'up':   #根据标记，向上找下一个
            p1 -= 1
    s.reverse()
    comman_index.reverse()
    return ''.join(s), comman_index




if __name__ == "__main__":
    with pdfplumber.open("documents/test.pdf") as pdf:
        pages = pdf.pages

        for page in pages:
            image = page.to_image(resolution=96)
            image.save("doc_images/test_Page"+str(page.page_number)+".png", format="png")
        doc1 = 1
        doc2 = 2
        page1 = pages[doc1-1]
        page2 = pages[doc2-1]
        chars1 = page1.chars
        chars2 = page2.chars
        text1 = []
        text2 = []
        # print(chars1[0])
        for item in chars1:
            text1.append(item["text"])
        for item in chars2:
            text2.append(item["text"])
        text1 = "".join(text1)
        text2 = "".join(text2)
        len1 = len(text1)
        len2 = len(text2)
        comman_string, comman_index = find_lcseque(text1, text2)
        page_cnt = 1
        tmp_image = cv2.imread("doc_images/test_Page"+str(page_cnt)+".png")

        for index in comman_index:
            width = int(float(chars1[index]["width"])*1.33)
            height = int(float(chars1[index]["height"])*1.33)
            x = int(float(chars1[index]["x0"])*1.33)
            y = int(float(chars1[index]["top"])*1.33)
            for i in range(width):
                tmp_image[y][x+i] = [0, 0, 255]
                tmp_image[y+height][x+i] = [0, 0, 255]
            for j in range(height):
                tmp_image[y+j][x] = [0, 0, 255]
                tmp_image[y+j][x+width] = [0, 0, 255]
        cv2.imwrite("result.png", tmp_image)